﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class MusicMgr : BaseManager<MusicMgr>
{
    private AudioSource bgMusic = null;
    private float bgValue = 1;

    private GameObject soundObj = null;
    private List<AudioSource> soundList = new List<AudioSource>();
    private float soundValue = 1;
    public MusicMgr()
    {
        MonoManager.GetInstance().AddUpdateListener(MusicUpdate);
    }
    //使用Mono公共类进行帧更新
    private void MusicUpdate()
    {
        for (int i = soundList.Count - 1; i > 0; --i)
        {
            if (!soundList[i].isPlaying)
            {
                GameObject.Destroy(soundList[i]);
                soundList.RemoveAt(i);
            }
        }
    }
    public void PlaySound(string name,bool isLoop,UnityAction<AudioSource>callback = null)
    {
        if (soundObj == null)
        {
            soundObj = new GameObject();
            soundObj.name = "Sound";
        }
        ResManager.GetInstance().LoadAsync<AudioClip>(name, (clip) =>
        {
            AudioSource source = soundObj.AddComponent<AudioSource>();
            source.clip = clip;
            source.loop = isLoop;
            source.volume = soundValue;
            source.Play();
            soundList.Add(source);
            if (callback != null)
                callback(source);
        });
    }
    public void ChangeSoundValue(float value)
    {
        soundValue = value;
        for(int i = 0; i < soundList.Count; i++)
        {
            soundList[i].volume = value;
        }
    }

    public void StopSound(AudioSource source)
    {
        soundList.Remove(source);
        source.Stop();
        GameObject.Destroy(source);
    }

    public void PlayBGM(string name)
    {
        if (bgMusic == null)
        {
            GameObject obj = new GameObject();
            obj.name = "BGM";
            bgMusic = obj.AddComponent<AudioSource>();
        }
        ResManager.GetInstance().LoadAsync<AudioClip>(name, (clip) =>
         {
             bgMusic.clip = clip;
             bgMusic.loop = true;
             bgMusic.volume = bgValue;
             bgMusic.Play();
         });
    }
    

    public void PauseBGM()
    {
        if(bgMusic == null)
            return;
        
        bgMusic.Pause();
    }
    public void StopBGM()
    {
        if (bgMusic == null)
            return;
        
        bgMusic.Stop();
    }
    public void ChangeBGMVolume(float volume)
    {
        bgValue = volume;
        if (bgMusic == null)
            return;
        bgMusic.volume = bgValue;
    }
}
